package client

import (
	"net/url"

	"github.com/eyotang/boomer"
	"github.com/valyala/fasthttp"
)

type Request struct {
	c       *Client
	request *fasthttp.Request

	name string
	ctx  boomer.Context
	cf   CheckFunc

	Error error
}

func (r *Request) SetFastHttpRequestBody(body []byte) *Request {
	r.request.SetBody(body)
	return r
}

func NewRequest(c *Client, ctx boomer.Context, name string, cf CheckFunc) *Request {
	request := fasthttp.AcquireRequest()
	return &Request{
		c:       c,
		request: request,
		ctx:     ctx,
		name:    name,
		cf:      cf,
	}
}

func (r *Request) Do() *Request {
	r.c.Do(r)
	fasthttp.ReleaseRequest(r.request)

	return r
}

func ParseURI(urlStr string) (URI string) {
	var (
		err     error
		baseURL *url.URL
	)
	if baseURL, err = url.Parse(urlStr); err != nil {
		return "/"
	}
	if baseURL.Path == "" {
		return "/"
	}
	return baseURL.Path
}
func (r *Request) GetErrors() []error {
	if errs, ok := r.Error.(Errors); ok {
		return errs
	} else if r.Error != nil {
		return []error{r.Error}
	}
	return []error{}
}

func (r *Request) AddError(err error) error {
	if err != nil {
		errors := Errors(r.GetErrors())
		errors = errors.Add(err)
		if len(errors) > 1 {
			err = errors
		}

		r.Error = err
	}
	return err
}

func (r *Request) Header(headers map[string]string) *Request {
	for k, v := range headers {
		r.request.Header.Set(k, v)
	}
	return r
}

func (r *Request) URL(url string) *Request {
	r.request.SetRequestURI(url)
	return r
}

func (r *Request) POST() *Request {
	r.request.Header.SetMethod("POST")
	return r
}

func (r *Request) GET() *Request {
	r.request.Header.SetMethod("GET")
	return r
}

func (r *Request) Host(host string) *Request {
	r.request.SetHost(host)
	r.request.Header.SetHost(host)
	return r
}
